<?php

if (!(defined('IN_IA'))) 
{
    exit('Access Denied');
}

class List_MxShopPage extends WebPage {

    function main() {

        global $_W, $_GPC;
        $pindex = max(1, intval($_GPC['page']));
        $psize = 20;
        $condition = "";
        $params = array();
        if (!empty($_GPC['mid'])) {
            $condition.=' and dm.id=:mid';
            $params[':mid'] = intval($_GPC['mid']);
        }
        if (!empty($_GPC['realname'])) {
            $_GPC['realname'] = trim($_GPC['realname']);
            $condition.=' and ( dm.realname like :realname or u.nickname like :realname or dm.mobile like :realname or u.openid like :realname)';
            $params[':realname'] = "%{$_GPC['realname']}%";
        }
        if (empty($starttime) || empty($endtime)) {
            $starttime = strtotime('-1 month');
            $endtime = time();
        }

        if (!empty($_GPC['time']['start']) && !empty($_GPC['time']['end'])) {
            $starttime = strtotime($_GPC['time']['start']);
            $endtime = strtotime($_GPC['time']['end']);
            $condition .= " AND dm.createtime >= :starttime AND dm.createtime <= :endtime ";
            $params[':starttime'] = $starttime;
            $params[':endtime'] = $endtime;
        }
        if ($_GPC['level'] != '') {
            $condition.=' and dm.levelid=' . intval($_GPC['level']);
        }
        if ($_GPC['groupid'] != '') {
            $condition.=' and dm.groupid=' . intval($_GPC['groupid']);
        }
        $join = " left join " . tablename('mx_shop_user') . " du on du.uuid=dm.parent_uuid";
        $join .= " left join " . tablename('mx_shop_userinfo') . " u on u.uid=dm.id and u.uniacid=".$_W['platformid'];
        $join .= " left join " . tablename('mx_shop_user_group') . " g on g.id=dm.groupid and g.uniacid=".$_W['platformid'];
        $join .= " left join " . tablename('mx_shop_user_level') . " l on l.id=dm.levelid and l.uniacid=".$_W['platformid'];
        if ($_GPC['followed'] != '') {
            if ($_GPC['followed'] == 2) {
                $condition.=' and f.follow=0 and f.unfollowtime<>0';
            } else {
                $condition.=' and f.follow=' . intval($_GPC['followed']). ' and f.unfollowtime=0 ';
            }
            $join .= " left join " . tablename('mc_mapping_fans') . " f on f.openid=u.openid";
        }
        if ($_GPC['isblack'] != '') {
            $condition.=' and dm.isblack=' . intval($_GPC['isblack']);
        }
        $sql = "select dm.*,u.avatar as uavatar, u.realname as urealname, u.openid, u.nickname, g.groupname, l.levelname, du.realname as parentname, du.avatar as parentavatar from " . tablename('mx_shop_user') . " dm {$join} where 1 {$condition}  ORDER BY id DESC";
        if (empty($_GPC['export'])) {
            $sql.=" limit " . ($pindex - 1) * $psize . ',' . $psize;
        }else{
            ini_set('memory_limit','-1');
        }
        $list = pdo_fetchall($sql, $params);

        $list_fans = array();
        foreach ($list as $val) {
            $list_fans[] = trim($val['openid'],',');
        }
        isset($list_fans) && $list_fans = array_values(array_filter($list_fans));
        if (!empty($list_fans)){
            $res_fans = pdo_fetchall("select fanid,openid,follow as followed, unfollowtime from " . tablename('mc_mapping_fans') . " where openid in ('".implode('\',\'',$list_fans)."')",array(),'openid');
        }

        $shop = m('common')->getSysset('shop');
        foreach ($list as &$row) {
            $row['followed'] = isset($res_fans[$row['openid']]) ? $res_fans[$row['openid']]['followed'] : '';
            $row['unfollowtime'] = isset($res_fans[$row['openid']]) ? $res_fans[$row['openid']]['unfollowtime'] : '';
            $row['fanid'] = isset($res_fans[$row['openid']]) ? $res_fans[$row['openid']]['fanid'] : '';
            $row['levelname'] = empty($row['levelname']) ? (empty($shop['levelname']) ? '普通会员' : $shop['levelname']) : $row['levelname'];
            $row['ordercount'] = pdo_fetchcolumn('select count(*) from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3', array(':uniacid' => $_W['platformid'], ':openid' => $row['openid']));
            $row['ordermoney'] = pdo_fetchcolumn('select sum(price) from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3', array(':uniacid' => $_W['platformid'], ':openid' => $row['openid']));
            $row['credit1'] = m('userinfo')->getCredit($row['id'], 'credit1');
            $row['credit2'] = m('userinfo')->getCredit($row['id'], 'credit2');
            $row['avatar'] = empty($row['avatar']) ? tomedia($row['uavatar']) : tomedia($row['avatar']);
            $row['realname'] = empty($row['realname']) ? $row['urealname'] : $row['realname'];
        }
        unset($row);

        //导出Excel
        if ($_GPC['export'] == '1') {

            plog('user.list', '导出会员数据');
            foreach ($list as &$row) {
                $row['createtime'] = date('Y-m-d H:i', $row['createtime']);
                $row['groupname'] = empty($row['groupname']) ? '无分组' : $row['groupname'];
                $row['levelname'] = empty($row['levelname']) ? '普通会员' : $row['levelname'];
                $row['realname'] = str_replace('=', "", $row['realname']);
                $row['nickname'] = str_replace('=', "", $row['nickname']);
            }
            unset($row);

            m('excel')->export($list, array(
                "title" => "会员数据-" . date('Y-m-d-H-i', time()),
                "columns" => array(
                    array('title' => '昵称', 'field' => 'nickname', 'width' => 12),
                    array('title' => '姓名', 'field' => 'realname', 'width' => 12),
                    array('title' => '手机号', 'field' => 'mobile', 'width' => 12),
                    array('title' => 'openid', 'field' => 'openid', 'width' => 24),
                    array('title' => '会员等级', 'field' => 'levelname', 'width' => 12),
                    array('title' => '会员分组', 'field' => 'groupname', 'width' => 12),
                    array('title' => '注册时间', 'field' => 'createtime', 'width' => 12),
                    array('title' => '积分', 'field' => 'credit1', 'width' => 12),
                    array('title' => '余额', 'field' => 'credit2', 'width' => 12),
                    array('title' => '成交订单数', 'field' => 'ordercount', 'width' => 12),
                    array('title' => '成交总金额', 'field' => 'ordermoney', 'width' => 12)
                )
            ));
        }
        $total = pdo_fetchcolumn("select count(*) from" . tablename('mx_shop_user') . " dm {$join} where 1 {$condition} ", $params);
        $pager = pagination2($total, $pindex, $psize);

        $groups = m('userinfo')->getGroups();
        $levels = m('userinfo')->getLevels();

        $set = m('common')->getSysset();
        $default_levelname = empty($set['shop']['levelname']) ? '普通等级' : $set['shop']['levelname'];

        include $this->template();
    }

    function detail() {

        global $_W, $_GPC;

        $area_set = m('util')->get_area_config_set();

        $new_area = intval($area_set['new_area']);

        $shop = $_W['shopset']['shop'];

        $id = intval($_GPC['id']);

        $user = m('userinfo')->getUser($id);

        $user['self_ordercount'] = pdo_fetchcolumn('select count(*) from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3', array(':uniacid' => $_W['platformid'], ':openid' => $user['openid']));
        $user['self_ordermoney'] = pdo_fetchcolumn('select sum(price) from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3', array(':uniacid' => $_W['platformid'], ':openid' => $user['openid']));

        if (!empty($user['parent_uuid'])) {
            $parentagent = m('userinfo')->getUserByUuid($user['parent_uuid']);
        }

        $order = pdo_fetch('select finishtime from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status>=1 Limit 1', array(':uniacid' => $_W['platformid'], ':openid' => $user['openid']));
        $user['last_ordertime'] = $order['finishtime'];

        $groups = m('userinfo')->getGroups();
        $levels = m('userinfo')->getLevels();

        $openbind = false;
        if((empty($_W['shopset']['app']['isclose']) && !empty($_W['shopset']['app']['openbind'])) || !empty($_W['shopset']['wap']['open'])){
            $openbind = true;
        }


        if ($_W['ispost']) {

            $data = is_array($_GPC['data']) ? $_GPC['data'] : array();
            if($data['maxcredit']<0){
                $data['maxcredit'] = 0;
            }

            if($openbind){

                if(!empty($data['mobile'])){
                    $m = pdo_fetch('select id from ' . tablename('mx_shop_user') . ' where mobile=:mobile limit 1 ', array(':mobile'=>$data['mobile']));
                    if(!empty($m) && $m['id']!=$id){
                        show_json(0, "此手机号已绑定其他用户!(uid:".$m['id'].")");
                    }
                }

                $data['pwd'] = trim($data['pwd']);
                if(!empty($data['pwd'])){
                    $salt = $user['salt'];
                    if (empty($salt)) {
                        //生成识别码
                        $salt = m('account')->getSalt();
                    }
                    $data['pwd'] = md5($data['pwd'] . $salt);
                    $data['salt'] = $salt;
                }else{
                    unset($data['pwd']);
                    unset($data['salt']);
                }
            }


            pdo_update('mx_shop_user', $data, array('id' => $id));

            $user =array_merge($user,$data);

            plog('user.list.edit', "修改会员资料  ID: {$user['id']} <br/> 会员信息:  {$user['openid']}/{$user['nickname']}/{$user['realname']}/{$user['mobile']}");

            show_json(1);
        }

        $order = pdo_fetch('select finishtime from ' . tablename('mx_shop_order') . ' where uniacid=:uniacid and openid=:openid and status=3 order by id desc limit 1', array(':uniacid' => $_W['platformid'], ':openid' => $user['openid']));
        $user['last_ordertime'] = $order['finishtime'];

        include $this->template();
    }

    function recharge() {

        global $_W,$_GPC;
        $type = trim($_GPC['type']);

        $id = intval($_GPC['id']);
        $profile = m('userinfo')->getUser($id);
        if ($_W['ispost']) {
            $typestr = $type == 'credit1' ? '平台积分' : '通用积分';
            $num = floatval($_GPC['num']);
            $remark = trim($_GPC['remark']);
            if ($num <= 0) {
                show_json(0, array('message' => '请填写大于0的数字!'));
            }
            $changetype = intval($_GPC['changetype']);
            if ($changetype == 2) {
                $num-=$profile[$type];

            } elseif ($changetype == 1) {
                $num = -$num;
            }

            m('userinfo')->setCredit($profile['id'], $type, $num, array($_W['uid'], '后台会员充值' . $typestr . " " . $remark));

            $changetype =0;
            $changenum =0;
            if($num>=0)
            {
                $changetype=0;
                $changenum =$num;
            }else
            {
                $changetype=1;
                $changenum =0-$num;
            }

            if($type=='credit1'){
                m('notice')->sendMemberPointChange($profile['openid'],$changenum,$changetype);
            }

            if($type=='credit2'){
                $set = m('common')->getSysset('shop');
                $logno = m('common')->createNO('user_log', 'logno', 'UR');
                $data = array(
                    'openid' => $profile['openid'],
                    'logno' => $logno,
                    'uniacid' => $_W['platformid'],
                    'type' => '0',
                    'createtime' => TIMESTAMP,
                    'status' => '1',
                    'title' => $set['name'] . "会员充值",
                    'money' => $num,
                    'realmoney' => $num,
                    'remark' => $remark,
                    'rechargetype' => 0
                );
                pdo_insert('mx_shop_user_log', $data);
                $logid = pdo_insertid();
                m('notice')->sendMemberLogMessage($logid,0,true);
            }

            plog('user.list.' . $type, "充值{$typestr}: {$_GPC['num']} <br/>会员信息: ID: {$profile['id']} /  {$profile['realname']}/{$profile['mobile']}");
            show_json(1, array('url' => referer()));
        }

        include $this->template();
    }

    function delete() {

        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        if (empty($id)) {
            $id = is_array($_GPC['ids']) ? implode(',', $_GPC['ids']) : 0;
        }

        $users = pdo_fetchall("SELECT * FROM " . tablename('mx_shop_user') . " WHERE id in( $id ) ");
        foreach ($users as $user) {
            pdo_delete('mx_shop_user', array('id' => $user['id']));
            pdo_delete('mx_shop_userinfo', array('uid' => $user['id']));
            plog('user.list.delete', "删除会员  ID: {$user['id']} <br/>会员信息: {$user['realname']}/{$user['mobile']}");
        }
        show_json(1, array('url' => referer()));
    }

    function setblack() {

        global $_W, $_GPC;

        $id = intval($_GPC['id']);
        if (empty($id)) {
            $id = is_array($_GPC['ids']) ? implode(',', $_GPC['ids']) : 0;
        }
        $users = pdo_fetchall("select id,realname,mobile from " . tablename('mx_shop_user')  . " WHERE id in( {$id} )");

        $black = intval($_GPC['isblack']);
        foreach($users as $user) {
            if (!empty($black)) {
                pdo_update('mx_shop_user', array('isblack' => 1), array('id' => $user['id']));
//                pdo_update('mx_shop_userinfo', array('isblack' => 1), array('uid' => $user['id'], 'uniacid'=>$_W['platformid']));
                plog('user.list.edit', "设置黑名单 <br/>用户信息:  ID: {$user['id']} /  {$user['realname']}/{$user['mobile']}");
            } else {
                pdo_update('mx_shop_user', array('isblack' => 0), array('id' => $user['id']));
//                pdo_update('mx_shop_userinfo', array('isblack' => 0), array('uid' => $user['id'], 'uniacid'=>$_W['platformid']));
                plog('user.list.edit', "取消黑名单 <br/>用户信息:  ID: {$user['id']} /  {$user['realname']}/{$user['mobile']}");
            }
        }
        show_json(1);
    }

    function changelevel() {
        global $_W, $_GPC;

        if($_W['ispost']){
            $toggle = trim($_GPC['toggle']);
            $ids = $_GPC['ids'];
            $levelid = intval($_GPC['level']);
            if(empty($ids) || !is_array($ids)){
                show_json(0, "请选择要操作的会员");
            }
            if(empty($toggle)){
                show_json(0, "请选择要操作的类型");
            }
            $ids = array_filter($ids);
            $idsstr = implode(',', $ids);
            $loginfo = "批量修改";

            if($toggle=='group'){
                if(!empty($levelid)){
                    $group = pdo_fetch('select * from ' . tablename('mx_shop_user_group') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $levelid, ':uniacid' => $_W['platformid']));
                    if(empty($group)){
                        show_json(0, "此分组不存在");
                    }
                }else{
                    $group = array('groupname'=>'无分组');
                }
                $arr = array('groupid'=>$levelid);
                $loginfo .= "用户分组 分组名称：".$group['groupname'];
            }else{
                if(!empty($levelid)) {
                    $level = pdo_fetch('select * from ' . tablename('mx_shop_user_level') . ' where id=:id and uniacid=:uniacid limit 1', array(':id' => $levelid, ':uniacid' => $_W['platformid']));
                    if (empty($level)) {
                        show_json(0, "此等级不存在");
                    }
                }else{
                    $set = m('common')->getSysset();
                    $level = array('levelname'=>empty($set['shop']['levelname']) ? '普通等级' : $set['shop']['levelname']);
                }
                $arr = array('level'=>$levelid);
                $loginfo .= "用户等级 等级名称：".$level['levelname'];
            }
            
            $changeids = array();

            $users = pdo_fetchall("select id,openid,nickname,realname,mobile from " . tablename('mx_shop_user')  . " WHERE id in( $idsstr ) ");
            if(!empty($users)){
                foreach ($users as $user) {
                    pdo_update('mx_shop_user', $arr, array('id' => $user['id']));
                    $changeids[] = $user['id'];
                }
            }

            if(!empty($changeids)){
                $loginfo .= " 用户id：". implode(",", $changeids);
                plog('user.list.edit', $loginfo);
            }

            show_json(1);
        }


        include $this->template();
    }

    function query() {

        global $_W, $_GPC;
        $kwd = trim($_GPC['keyword']);
        $wechatid = intval($_GPC['wechatid']);
        if (empty($wechatid)) {
            $wechatid = $_W['platformid'];
        }
        $params = array();
        $params[':uniacid'] = $wechatid;
        $condition = " and uniacid=:uniacid";
        if (!empty($kwd)) {
            $condition.=" AND ( `nickname` LIKE :keyword or `realname` LIKE :keyword or `mobile` LIKE :keyword )";
            $params[':keyword'] = "%{$kwd}%";
        }
        $ds = pdo_fetchall('SELECT id,avatar,nickname,openid,realname,mobile FROM ' . tablename('mx_shop_user') . " WHERE 1 {$condition} order by createtime desc", $params);
        if ($_GPC['suggest']) {
            die(json_encode(array('value' => $ds)));
        }
        include $this->template();
    }



}
